<?php

$this->useClass("Handler_Comments");
/*
 * TODO: 61: Я предлагаю следующий рефакторинг. Нужно большой switch внизу вынести в отдельные классы, и создать
 * для них суперкласс в обязанности которого вынести например вызов getContent() и выбор нужного шаблона.
 *
 * Метод determine view научить инстанцировать нужный класс.
 *
 */
class Action_Community_ShowItem extends Handler_Comments
{

	private function determineView($a) {
		$parent_oid = $a["parent_oid"];
		$offset = $a['offset'];
		$submit = $a['submit'];
		$showcomments = $a['showcomments'];
		$comment_oid = $a['comment_oid'];

		if ($parent_oid && isset($submit)) {
			// от нас хотят ответ к $parent_oid комменту: сам коммент и форму сабмита
			return "answer_to_parent";
		} elseif ($parent_oid && isset($showcomments)) {
			// хотят показать детей какого-нибудь коммента
			return "thread_view";
		} elseif ($comment_oid) {
			// хотят показать обновление формы
			return "update_form";
		} elseif (isset($showcomments)) {
			// хотят раскрыть комментарии с самого начала
			return "comments_init_state";
		}

		return "";
	}

	private function getOneItem( $item_oid ) {
		if ($item_oid==null) {
			return array();
		}

		$this->rh->UseClass("AggregatedModel_Feed_FeedInterface");
		$this->rh->UseClass("AggregatedModel_Feed_ReaderItems");

		$rdr = new AggregatedModel_Feed_ReaderItems();
		$rdr->rh = $this->rh;
		$rdr->setModelParams("community_oid", $this->aa->acl_data['comity_oid']);
		$rdr->setModelParams("item_oid", $item_oid);
		$rdr->setModelParams("page_number", 1);
		$rdr->setModelParams("page_citems", 1);

		$rdr->doStuff();

		list($item) = $rdr->getItems();

		// FIXME : 2008-05-20 : lucky
		// -- специфичный форматтер для итема типа "голосование" -- {{{
		if ($item['post']['type'] == 'fvote') {
			// установить bool $item['voted'] если текущий пользователь голосовал
			$vm = $this->ctx->mm->getModel("Vote", "m");
			$aa = $this->aa;
			$item['already_voted'] = $vm->checkUserVote($item['post']['oid'], $aa->acl_data['user_id']);

			// создать ссылку на голосоватор за данный итем
			$this->ctx->rh->useClass('RL_URLGenerator');
			$ug = new RL_URLGenerator($this->rh->router->getRule("vote_manager")); //
			$ug->setRouter($this->rh->router);
			$ug->setParams(array(
				"community_url"=>$this->params['community_url'],
				"id_item"=>$item['post']['oid'],
				)
			);
			$item['vote_url'] = $ug->generateUrl();
			unset($ug);

			if ($item['post']['posted_by_id'] == $this->aa->acl_data['user_id']) {
					if ( $item['vote_closed'] ) {
						$item['can_open'] = 1;
					} else {
						$item['can_close'] = 1;
					}
			}
		}
		// -- специфичный форматтер для итема типа "голосование" -- }}}

		// -- раздел, где опубликован итем -- {{{
		$m_tdi = $this->ctx->mm->getModel("Tdi", "m");
		$item_tdi = $m_tdi->getTdi($item['post']['tdi_oid']);
		if ($item_tdi) {
			// собственно данные о разделе
			$item['tdi'] = $item_tdi->data;

			// ссылка на раздел
			$this->rh->UseClass("RL_URLGenerator");
			$ug = new RL_URLGenerator($this->rh->router->getRule("community_tdi")); //
			$ug->setRouter($this->rh->router);
			$ug->setParams(array(
				"community_url"=>$this->params['community_url'],
				"tdi_url"=>$item['tdi']['url'],
				)
			);
			$item['tdi_url'] = $ug->generateUrl();
		}
		// -- раздел, где опубликован итем -- }}}


		return $item;

	}

	public function process ()
	{
		$this->rh->UseClass('RL_CyrDate');
		$aa = $this->module->aa;
		$this->aa = $aa;

		$this->data = $data = $aa->getInfo();

		// проверка прав
		$aa->getAvailableOperations();
		if ( !$aa->is_granted( array( 'item_read') ) ) { echo "access denied"; return false; }

		$this->ctx->mm->setAclAssistant( $aa );
		$aa->checkDeletions( array($this, "shutdown") );

		// прицепим необходимую модель данных
		$this->m_item = $this->ctx->mm->getModel("Item", "a");
		$this->m_issue = $this->ctx->mm->getModel("Issue", "m");

		$item = $this->getOneItem( $this->params['id_item'] );

		/**
		 * если какой юзер правил топик, надо подтянуть его данные
		 */
		if ( isset($item['post']['edited_user_oid']) && !empty($item['post']['edited_user_oid']) ) {
			$object = $this->ctx->store->getObject($item['post']['edited_user_oid']);
			$item['post']['edited_user'] = $object->data;
		}

		$issue_set = $this->m_issue->getIssueSetByItemOid( $this->params['id_item'] );

		$view = $this->rh->views->findByName('post');
		$view->data = $aa->template_data;
		//!!!!!!!!!КВЕСТ
		$qModel = $this->ctx->mm->getModel("Quest");
//		$oItem = $qModel->getItem($this->params['id_item']);
		$view->data['quests'] = $qModel->getQuestActions($item);

		// права юзера
		$view->data['can_create'] = $aa->is_granted(array('item_create', 'item_create_premod'));
		$view->data['can_comment'] = $aa->is_granted(array('comment_create_premod', 'comment_create'));

		// свойства итема и среды для ссылок
		$view->data['item_oid'] = $item['post']['oid'];
		$view->data['parent_oid'] = isset($this->rh->GET['parent_oid']) ? $this->rh->GET['parent_oid'] : $item['post']['oid'];
		$view->data['community_id'] = $data['community_id'];

		// контент итема
		// 61, 24-03-2008
		// Этот кусочек скопипасчен из ShowFeed суть в том что это логика типа "Голосования" о том как его отображать в ленте
		// те это вполне можно откладывать в отдельный класc или может быть еще как-то
		if ($item['post']['type'] == 'fvote') {
			$this->rh->UseClass("RL_URLGenerator");
			$ug = new RL_URLGenerator($this->rh->router->getRule("vote_manager")); //
			$ug->setRouter($this->rh->router);
			$ug->setParams(array(
				"community_url"=>$this->params['community_url'],
				"id_item"=>$item['post']['oid'],
				)
			);
			$item['vote_url'] = $ug->generateUrl();
			unset($ug);

			if ($item['post']['posted_by_id'] == $aa->acl_data['user_id']) {
					if ( $item['vote_closed'] ) {
						$item['can_open'] = 1;
					} else {
						$item['can_close'] = 1;
					}
			}
			$item['can_vote'] = (isset($aa->acl_data['user_id'])) ? true : false;
		}

		$view->data['tmp'] = $item;
		$view->data['tmp']['acl'] = $aa->getAcl( $item['post']['oid'] );
		$view->data['tmp']['issue_number'] = $issue_set['issue_number'];

		switch ($this->determineView($this->rh->GET)) {
		case "comments_init_state":
			$view->data['showcontainer'] = true;
			$tc = $this->ctx->mm->getModel("TreeComments", "m");
			$tc->setTCparams();
			list($comments, $loader_type2) = $tc->getComments( $this->params['id_item'], $this->params['id_item'] );

			foreach ($comments as $i=>$com) {
				$comments[ $i ]['acl'] = $aa->getAcl( $com['oid'] );
			}

			$view->data['comments'] = array( "items"=>$comments, "count"=>count($comments) );

			$view->data['loader_type2'] = $loader_type2;

			$view_comments = $this->rh->views->findByName('comments');
			$view_comments->data = $view->data;

			// форма сабмита
			$view_comments->data['user']['date'] = RL_CyrDate::newNow();
			$view_comments->data['user']['oid'] = $this->data['user_id'];
			$view_comments->data['user']['avatar'] = $this->data['user']['avatar'];
			$view_comments->data['user']['url'] = $this->data['user_id'];

			$view->data['rendered_comment_container'] = $view_comments->getContent();
			unset($view_comments);
			break;

		case "thread_view":
			$view->data['showcontainer'] = true;
			$tc = $this->ctx->mm->getModel("TreeComments", "m");
			$tc->setTCparams();
			list($comments, $loader_type2) = $tc->getComments( $this->rh->GET['parent_oid'], $this->params['id_item'], $this->rh->GET['offset'] );
			$offset_delta = $comments[0]['offset'];
			foreach ($comments as $i=>$com) {
				$comments[ $i ]['acl'] = $aa->getAcl( $com['oid'] );
				$comments[ $i ]['offset'] -= $offset_delta;
			}
			$view->data['comments'] = array( "items"=>$comments, "count"=>count($comments) );
			$view->data['loader_type2'] = $loader_type2;

			$view->data['parent_comment'] = $this->getOneComment( $this->rh->GET['parent_oid'] );

			$view_comments = $this->rh->views->findByName('comments_only_comments');
			$view_comments->data = $view->data;

			$view->data['rendered_comment_container'] = $view_comments->getContent();
			unset($view_comments);

			break;

		case "answer_to_parent":
			$view->data['showcontainer'] = true;
			$view->data['comments']["count"] = $this->ctx->mm->getModel("FlatComments", "m")->commentsCount($this->params['id_item']);

			$p_comment = $this->getOneComment( $this->rh->GET['parent_oid'] );
			$view_comments = $this->rh->views->findByName('comments_answer_to_parent');
			$view_comments->data = $view->data;

			$view_comments->data['comments']['items'][0] = $p_comment;
			$view_comments->data['comments']['items'][0]['offset'] = 0;
			// форма сабмита
			$view_comments->data['user']['date'] = RL_CyrDate::newNow();
			$view_comments->data['user']['oid'] = $this->data['user_id'];
			$view_comments->data['user']['avatar'] = $this->data['user']['avatar'];
			$view_comments->data['user']['url'] = $this->data['user_id'];

			$view->data['rendered_comment_container'] = $view_comments->getContent();
			unset($view_comments);

			break;

		case "update_form":
			$view->data['showcontainer'] = true;
			$view->data['comments']["count"] = $this->ctx->mm->getModel("FlatComments", "m")->commentsCount($this->params['id_item']);
			$u_comment = $this->getOneComment( $this->rh->GET['comment_oid'] );
			$view_comments = $this->rh->views->findByName('comments_update_form');
			$view_comments->data = $view->data;
			$view_comments->data['comment_oid'] = $this->rh->GET['comment_oid'];
			$view_comments->data['comment'] = $u_comment;
			$view->data['rendered_comment_container'] = $view_comments->getContent();
			unset($view_comments);

			break;

		default:
			$view->data['comments']["count"] = $this->ctx->mm->getModel("FlatComments", "m")->commentsCount($this->params['id_item']);
			break;
		}

		$view->data['__widgets__'] = $this->widgets;

		$this->rh->response->setContent( $view );

		// -- touch visitor stat -- {{{
		// visit  tdi
		$this->ctx->mm->getModel("Visitable", "m")->getVisitable('Item')->setWhat($this->params['id_item'])->visit();
		//
		// -- touch visitor stat -- }}}

	} // end of function execute

	public function getWidgetsConfig ()
	{
		$widgets = array();

		$widgets[] = array (
			'name' => 'CreateBtnWidget',
			'params' => array(
				'widget_position' => 'createbtn',
				'widget_view' => 'WG_CreateBtnWidget',
			),

		);

		$widgets[] = array (
			'name' => 'RssWidget',
			'params' => array(
				'widget_view' => 'WG_RssWidget',
			),
		);

		return $widgets;
	} // end of function getWidgetsConfig

}
